var timerId=0;
var timer_search_wait_milliseconds = 100;
var $LIMIT_FOR_AMOUNT_OF_LETTERS = 3;
var oldValue=null;
var search_form=null;

$(document).ready(

  function()
  {
    $('#search_keywords').keyup(
     function (key)
      {
        var $input = $(this);
        search_form = ($input).parents('form');
        
        clearTimeout(timerId);
        timerId = setTimeout(
          // call-back function when timer will ring
          function()
          {
            // DO introduce method: function getRequestString(var inputString)
            this.value = '';
            var buf = $input.val();		// buffer in which input string is saved
            var start = 0;				// index in buffer of first letter of next word
            var wordIsFirst = true;		// =true if no one word has not been added to the result request-string.
            for (var i=0; i < buf.length; i++)
            {
              // skip spaces before the word:
              for (; i < buf.length; i++) {
                if (buf[i] != ' ')
                  break;
              }

              start = i;

              // "read" the word:
              for (; i < buf.length; i++) {
                if (buf[i] == ' ')
                  break;
              }
              
              // check if some word is very small:
              if (i - start < $LIMIT_FOR_AMOUNT_OF_LETTERS)
                return;

               // append need special search symbols:
              if (wordIsFirst) {
                this.value = buf.substring(start, i) + '*';
                wordIsFirst = false;
              }
              else {
                  this.value = this.value + " + " + buf.substring(start, i) + '*';
              }
            }


            if (oldValue != this.value && this.value.length >= $LIMIT_FOR_AMOUNT_OF_LETTERS && this.value != '')
            {
              $('#loader').show();
              var data = search_form.serializeArray();
              $('#documents').load(
                search_form.attr('action'),
                data,
                function(){$('#loader').hide()}
              );
              
              oldValue = this.value;
              
            }
          },
          // time in millese
          
          timer_search_wait_milliseconds
        );
        
      }
  );

    $('.search_params').click(
     function ()
      {
         if (oldValue)
         {
             $('#loader').show();
             var data = search_form.serializeArray();
             $('#documents').load(
                search_form.attr('action'),
                data,
                function(){$('#loader').hide()}
              );
         }
      }
     );

  }
  )
